{% extends "admin/layout.html" %}
{% set active_page = 'groups' %}

{% block content %}
<div class="container-fluid px-4 py-3">
    <!-- 标题区域 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="d-flex align-items-center">
            <a href="{{ url_for('wxwork.group_management') }}" class="btn btn-outline-secondary me-3 rounded-pill">
                <i class="fas fa-arrow-left me-2"></i>返回列表
            </a>
            <h3 class="mb-0 text-dark"><i class="fas fa-users me-2 text-primary"></i>群组详情：{{ group.name }}</h3>
        </div>
        <div>
            <button class="btn btn-primary me-2 rounded-pill" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                <i class="fas fa-user-plus me-2"></i>添加成员
            </button>
            <form method="POST" action=" " class="d-inline"
                  onsubmit="return confirm('确定要解散该群组吗？此操作不可撤销！')">
                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-danger rounded-pill">
                    <i class="fas fa-trash-alt me-1"></i>解散群组
                </button>
            </form>
        </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="row mb-4 g-4">
        <!-- 左侧信息栏 -->
        <div class="col-lg-6">
            <!-- 群公告 -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center border-bottom">
                    <h5 class="mb-0 text-dark"><i class="fas fa-bullhorn me-2 text-warning"></i>群公告</h5>
                    <button class="btn btn-sm btn-outline-secondary rounded-pill" data-bs-toggle="modal"
                            data-bs-target="#editAnnouncementModal">
                        <i class="fas fa-edit me-1"></i>编辑
                    </button>
                </div>
                <div class="card-body bg-light">
                    {% if group.announcement %}
                    <div class="alert alert-light bg-white border-start border-3 border-warning p-3">
                        <div class="d-flex">
                            <i class="fas fa-quote-left text-muted me-2 mt-1"></i>
                            <p class="mb-0">{{ group.announcement }}</p>
                        </div>
                    </div>
                    {% else %}
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-info-circle fa-2x mb-2 text-secondary"></i>
                        <p class="mb-0">暂无群公告</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- 群组基本信息 -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0 text-dark"><i class="fas fa-info-circle me-2 text-info"></i>基本信息</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="d-flex align-items-center mb-3">
                                <div class="bg-light rounded-circle p-2 me-3">
                                    <i class="fas fa-tag text-primary"></i>
                                </div>
                                <div>
                                    <div class="text-muted small">群名称</div>
                                    <div class="fw-bold text-dark">{{ group.name }}</div>
                                </div>
                            </div>

                            <div class="d-flex align-items-center">
                                <div class="bg-light rounded-circle p-2 me-3">
                                    <i class="fas fa-crown text-warning"></i>
                                </div>
                                <div>
                                    <div class="text-muted small">群主</div>
                                    <div class="fw-bold text-dark">{{ group.owner.name }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="d-flex align-items-center mb-3">
                                <div class="bg-light rounded-circle p-2 me-3">
                                    <i class="fas fa-hashtag text-success"></i>
                                </div>
                                <div>
                                    <div class="text-muted small">企业微信ChatID</div>
                                    <div class="fw-bold text-dark"><code>{{ group.chat_id }}</code></div>
                                </div>
                            </div>

                            <div class="d-flex align-items-center">
                                <div class="bg-light rounded-circle p-2 me-3">
                                    <i class="fas fa-calendar-plus text-info"></i>
                                </div>
                                <div>
                                    <div class="text-muted small">创建时间</div>
                                    <div class="text-dark">{{ group.created_at.strftime('%Y-%m-%d %H:%M') }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="d-flex align-items-center">
                                <div class="bg-light rounded-circle p-2 me-3">
                                    <i class="fas fa-power-off text-{{ 'success' if group.status == 1 else 'danger' }}"></i>
                                </div>
                                <div>
                                    <div class="text-muted small">状态</div>
                                    <span class="badge bg-{{ 'success' if group.status == 1 else 'danger' }} rounded-pill px-3 py-1">
                                        {{ '活跃' if group.status == 1 else '已解散' }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧标签管理 -->
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0 text-dark"><i class="fas fa-tags me-2 text-primary"></i>标签管理</h5>
                </div>
                <div class="card-body">
                    <div class="mb-4">
                        <label class="form-label fw-bold mb-2 text-muted">当前关联标签</label>
                        <div class="d-flex flex-wrap gap-2">
                            {% if group.assigned_tags %}
                                {% for tag in group.assigned_tags.split(',') %}
                                    {% if tag.strip() %}
                                        <span class="badge bg-primary d-flex align-items-center rounded-pill px-3 py-2">
                                            <i class="fas fa-tag me-1"></i>
                                            {{ tag.strip() }}
                                            <a href="{{ url_for('wxwork.remove_group_tag', group_id=group.id, tag=tag.strip()) }}"
                                               class="text-white ms-2" title="移除标签">
                                                <i class="fas fa-times fa-sm"></i>
                                            </a>
                                        </span>
                                    {% endif %}
                                {% endfor %}
                            {% else %}
                                <div class="alert alert-light text-center w-100 py-3">
                                    <i class="fas fa-tag fa-2x text-muted mb-2"></i>
                                    <p class="mb-0 text-muted">未设置任何关联标签</p>
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold mb-2 text-muted">添加新标签</label>
                        <form method="POST" action="{{ url_for('wxwork.add_group_tags', group_id=group.id) }}">
                            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-tag text-muted"></i></span>
                                <input type="text" class="form-control" name="tags"
                                       placeholder="输入标签（多个用逗号分隔）">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-plus me-1"></i>添加
                                </button>
                            </div>
                            <small class="form-text text-muted">多个标签请用英文逗号分隔</small>
                        </form>
                    </div>

                    <!-- 标签同步操作按钮 -->
                    {% if group.assigned_tags %}
                    <div class="mb-4">
                        <label class="form-label fw-bold mb-2 text-muted">标签同步操作</label>
                        <div class="d-grid gap-2">
                            <form method="POST" action="{{ url_for('wxwork.sync_group_by_tags', group_id=group.id) }}" class="d-inline">
                                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                                <button type="submit" class="btn btn-success w-100">
                                    <i class="fas fa-sync me-1"></i>同步标签成员
                                </button>
                            </form>

                            <form method="POST" action="{{ url_for('wxwork.remove_non_matching_members', group_id=group.id) }}" class="d-inline">
                                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                                <button type="submit" class="btn btn-warning w-100"
                                        onclick="return confirm('确定要移除不符合标签要求的成员吗？此操作将从企业微信群聊中移除这些成员！')">
                                    <i class="fas fa-user-times me-1"></i>移除不符合标签成员
                                </button>
                            </form>
                        </div>
                        <small class="form-text text-muted">
                            同步标签成员：将符合标签的用户添加到群组<br>
                            移除不符合标签成员：从群组中移除不符合标签要求的成员
                        </small>
                    </div>
                    {% endif %}

                    <div>
                        <label class="form-label fw-bold mb-2 text-muted">按标签添加成员</label>
                        <form method="POST" action="{{ url_for('wxwork.add_group_members_by_tags', group_id=group.id) }}">
                            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                            <div class="input-group">
                                <span class="input-group-text bg-light"><i class="fas fa-users text-muted"></i></span>
                                <input type="text" class="form-control" name="tags"
                                       placeholder="输入标签来添加成员">
                                <button type="submit" class="btn btn-info">
                                    <i class="fas fa-user-plus me-1"></i>添加成员
                                </button>
                            </div>
                            <small class="form-text text-muted">将拥有指定标签的用户添加到群组</small>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 成员管理 -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center border-bottom">
            <h5 class="mb-0 text-dark"><i class="fas fa-user-friends me-2 text-primary"></i>群成员管理（共{{ group.members.count() }}人）</h5>
            <div>
                <button class="btn btn-sm btn-outline-primary me-2 rounded-pill" type="button"
                        data-bs-toggle="collapse" data-bs-target="#addMemberForm">
                    <i class="fas fa-plus me-1"></i>添加成员
                </button>
                <button class="btn btn-sm btn-outline-secondary rounded-pill"
                        onclick="syncGroupMembers({{ group.id }})">
                    <i class="fas fa-sync me-1"></i>同步成员
                </button>
            </div>
        </div>

        <div class="collapse" id="addMemberForm">
            <div class="card-body bg-light">
                <form method="POST" action="{{ url_for('wxwork.add_group_members', group_id=group.id) }}">
                    <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                    <div class="row">
                        <div class="col-12 mb-3">
                            <div class="alert alert-info d-flex align-items-center py-2">
                                <i class="fas fa-info-circle me-2 fa-lg"></i>
                                <span class="small">请选择要添加到群组的成员</span>
                            </div>
                        </div>
                        {% for user in users %}
                        <div class="col-md-4 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox"
                                       name="user_ids" value="{{ user.id }}" id="member-{{ user.id }}">
                                <label class="form-check-label d-flex align-items-center" for="member-{{ user.id }}">
                                    <span class="avatar me-2">
                                        <i class="fas fa-user-circle text-primary fa-lg"></i>
                                    </span>
                                    <span>
                                        <span class="d-block">{{ user.name }}</span>
                                        <small class="text-muted">{{ user.wecom_userid }}</small>
                                    </span>
                                </label>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    <div class="d-flex justify-content-end mt-3">
                        <button type="submit" class="btn btn-primary rounded-pill px-4">
                            <i class="fas fa-plus-circle me-1"></i>确认添加所选成员
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4"><i class="fas fa-user me-1"></i>姓名</th>
                            <th><i class="fas fa-building me-1"></i>部门</th>
                            <th><i class="fas fa-briefcase me-1"></i>职位</th>
                            <th><i class="fas fa-id-card me-1"></i>企业微信ID</th>
                            <th><i class="fas fa-tags me-1"></i>标签</th>
                            <th><i class="fas fa-calendar-day me-1"></i>加入时间</th>
                            <th class="text-center pe-4"><i class="fas fa-cog me-1"></i>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for member in group.members %}
                        <tr class="border-top">
                            <td class="ps-4 fw-bold">
                                <i class="fas fa-user-circle me-2 text-primary"></i>
                                {{ member.user.name }}
                            </td>
                            <td>{{ member.user.department_name }}</td>
                            <td>{{ member.user.position }}</td>
                            <td><code>{{ member.user.wecom_userid }}</code></td>
                            <td>
                                {% if member.user.tags %}
                                    {% for tag in member.user.tags.split(',') %}
                                        <span class="badge bg-info rounded-pill me-1">{{ tag.strip() }}</span>
                                    {% endfor %}
                                {% else %}
                                    <span class="text-muted small">无标签</span>
                                {% endif %}
                            </td>
                            <td>{{ member.joined_at.strftime('%Y-%m-%d') }}</td>
                            <td class="text-center pe-4">
                                <form action="{{ url_for('wxwork.remove_group_member', group_id=group.id, user_id=member.user.id) }}" method="post">
                                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                    <button type="submit" class="btn btn-sm btn-outline-danger rounded-pill"
                                            onclick="return confirm('确定要从群组中移除 {{ member.user.name }} 吗？')">
                                        <i class="fas fa-user-minus me-1"></i>移除
                                    </button>
                                </form>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 编辑公告模态框 -->
<div class="modal fade" id="editAnnouncementModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form action="{{ url_for('wxwork.update_announcement', group_id=group.id) }}" method="post">
                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                <div class="modal-header bg-light">
                    <h5 class="modal-title text-dark"><i class="fas fa-bullhorn me-2 text-warning"></i>编辑群公告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <textarea class="form-control" name="content" rows="6"
                              placeholder="输入群公告内容">{{ group.announcement }}</textarea>
                    <div class="mt-2 text-muted small">
                        <i class="fas fa-lightbulb me-1"></i>提示：公告将发送给所有群成员
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary rounded-pill">保存修改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function syncGroupMembers(groupId) {
    const syncBtn = document.querySelector('[onclick="syncGroupMembers({{ group.id }})"]');
    const originalHtml = syncBtn.innerHTML;

    // 添加加载动画
    syncBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>同步中...';
    syncBtn.disabled = true;

    fetch(`/groups/${groupId}/sync_members`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    }).then(response => {
        if(response.ok) {
            // 同步成功效果
            syncBtn.innerHTML = '<i class="fas fa-check me-1"></i>同步成功';
            syncBtn.classList.remove('btn-outline-secondary');
            syncBtn.classList.add('btn-success');

            // 2秒后恢复原状
            setTimeout(() => {
                syncBtn.innerHTML = originalHtml;
                syncBtn.classList.remove('btn-success');
                syncBtn.classList.add('btn-outline-secondary');
                syncBtn.disabled = false;
            }, 2000);

            // 3秒后刷新页面
            setTimeout(() => location.reload(), 3000);
        } else {
            // 同步失败效果
            syncBtn.innerHTML = '<i class="fas fa-times me-1"></i>同步失败';
            syncBtn.classList.remove('btn-outline-secondary');
            syncBtn.classList.add('btn-danger');

            // 2秒后恢复原状
            setTimeout(() => {
                syncBtn.innerHTML = originalHtml;
                syncBtn.classList.remove('btn-danger');
                syncBtn.classList.add('btn-outline-secondary');
                syncBtn.disabled = false;
            }, 2000);
        }
    }).catch(error => {
        // 网络错误处理
        syncBtn.innerHTML = '<i class="fas fa-exclamation-triangle me-1"></i>网络错误';
        syncBtn.classList.remove('btn-outline-secondary');
        syncBtn.classList.add('btn-danger');

        // 2秒后恢复原状
        setTimeout(() => {
            syncBtn.innerHTML = originalHtml;
            syncBtn.classList.remove('btn-danger');
            syncBtn.classList.add('btn-outline-secondary');
            syncBtn.disabled = false;
        }, 2000);
    });
}
</script>
{% endblock %}